package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.util.ExcelImportUtil;
import com.guli.edu.entity.Subject;
import com.guli.edu.mapper.SubjectMapper;
import com.guli.edu.service.SubjectService;
import com.guli.edu.vo.SubjectNestedVo;
import com.guli.edu.vo.SubjectVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Frank
 * @since 2019-04-15
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    /**
     * 批量导入分类
     *
     * @param file Excel文件
     * @return 错误消息列表
     * @throws Exception
     */
    @Transactional
    @Override
    public List<String> bachImport(MultipartFile file) throws Exception {
        //错误消息
        ArrayList<String> errorMsg = new ArrayList<>();

        ExcelImportUtil excelHSSFUtil = new ExcelImportUtil(file.getInputStream());
        HSSFSheet sheet = excelHSSFUtil.getSheet();
        int rowCount = sheet.getPhysicalNumberOfRows();
        if (rowCount < -1) {
            errorMsg.add("请在表格中填写数据！");
            return errorMsg;
        }

        for (int rowNum = 1; rowNum < rowCount; rowNum++) {
            HSSFRow rowData = sheet.getRow(rowNum);
            if (rowData != null) {
                //获取一级分类
                String levelOneCellValue = "";
                HSSFCell levelOneCell = rowData.getCell(0);
                if (levelOneCell != null) {
                    levelOneCellValue = excelHSSFUtil.getCellValue(levelOneCell);
                    if (StringUtils.isEmpty(levelOneCellValue)) {
                        errorMsg.add("第" + (rowNum + 1) + "行一级分类为空");
                        continue;
                    }
                } else {
                    errorMsg.add("第" + (rowNum + 1) + "行一级分类为空");
                    continue;

                }
                //判断一级分类是否重复 TODO
                Subject subject = this.getByTitle(levelOneCellValue);
                String parentId = null;
                if (subject == null) {
                    //将一级分类存入数据库
                    Subject subjectLevelOne = new Subject();
                    subjectLevelOne.setTitle(levelOneCellValue);
                    subjectLevelOne.setSort(rowNum);
                    baseMapper.insert(subjectLevelOne);
                    parentId = subjectLevelOne.getId();

                } else {
                    parentId = subject.getId();
                }

                //获取二级分类
                String levelTowCellValue = "";
                HSSFCell levelTwoCell = rowData.getCell(1);
                if (levelTwoCell != null) {
                    levelTowCellValue = excelHSSFUtil.getCellValue(levelTwoCell);
                    if (StringUtils.isEmpty(levelTowCellValue)) {
                        errorMsg.add("第" + (rowNum + 1) + "行二级分类为空");
                        continue;
                    }
                } else {
                    errorMsg.add("第" + (rowNum + 1) + "行二级分类为空");
                    continue;
                }

                //判断二级分类是否重复
                Subject subjectParent = this.getByTitleAndParentId(levelTowCellValue, parentId);
                if (subjectParent == null) {
                    //将二级分类存入数据库
                    Subject subjectLevelTwo = new Subject();
                    subjectLevelTwo.setTitle(levelTowCellValue);
                    subjectLevelTwo.setSort(rowNum);
                    subjectLevelTwo.setParentId(parentId);
                    baseMapper.insert(subjectLevelTwo);
                }

            }
        }

        return errorMsg;
    }

    @Override
    public List<SubjectNestedVo> nestedList() {
        //最终要的到的数据列表
        ArrayList<SubjectNestedVo> subjectNestedVoArrayList = new ArrayList<>();
        //获取一级分类数据
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("parent_id", 0);
        subjectQueryWrapper.orderByAsc("sort","id");
        List<Subject> subjects = baseMapper.selectList(subjectQueryWrapper);
        //获取二级分类数据记录 TODO
        QueryWrapper<Subject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("parent_id", 0);
        queryWrapper2.orderByAsc("sort", "id");
        List<Subject> subSubjects = baseMapper.selectList(queryWrapper2);

        //填充一级分类vo数据
        int count = subjects.size();
        for (int i = 0; i < count; i++) {
            SubjectNestedVo subjectNestedVo = new SubjectNestedVo();
            Subject subject = subjects.get(i);
            subject.setTitle(subject.getTitle().trim());
            BeanUtils.copyProperties(subject, subjectNestedVo);
            subjectNestedVoArrayList.add(subjectNestedVo);

            //填充二级分类vo数据
            List<SubjectVo> subjectVoArrayList = new ArrayList<>();
            int count2 = subSubjects.size();
            for (int j = 0; j < count2; j++) {
                Subject subSubject = new Subject();
                subSubject = subSubjects.get(j);
               if(subSubject.getParentId().equals(subject.getId())){
                   //创建二级类别vo对象
                   SubjectVo subjectVo = new SubjectVo();
                   BeanUtils.copyProperties(subSubject, subjectVo);
                   subjectVoArrayList.add(subjectVo);
               }
            }
            subjectNestedVo.setChildren(subjectVoArrayList);
        }
        return subjectNestedVoArrayList;
    }

    /**
     * 根据分类名称查询这个一级分类中否存在
     *
     * @param title
     * @return
     */
    public Subject getByTitle(String title) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", 0);
        return baseMapper.selectOne(queryWrapper);

    }


    public Subject getByTitleAndParentId(String title, String parentId) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return baseMapper.selectOne(queryWrapper);
    }
}
